package com.dyava.commons.codec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;


public class AesCodec {
	   /**
     * AES java-javascript 只支持部填充摸索
     */
    public static final String format = "AES/ECB/PKCS5PADDING";
    /**
     * AES 加密key，必须为16位
     */
    public String key = "123456abc2345678";
    /**
     * AES 偏移量，必须为16位
     */
    public String iv = "123456abc2345678";

    SecretKeySpec keyspecAes;

    public AesCodec(String key) {
        this.key = key;
        try {
            keyspecAes = new SecretKeySpec(key.getBytes("utf-8"), "AES");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 使用AES加密
     * @since 0.0.11
     */
    public String encrypt(String data){
        if(StringUtils.isEmpty(data)){
            return null;
        }
        try {
            byte[] encrypted= encrypt(data.getBytes("utf-8"));
            return Base64.encodeBase64String(encrypted);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 使用AES加密
     * @since 0.0.11
     */
    public byte[] encrypt(byte[] dataBytes){
        if(dataBytes==null){
            return null;
        }
        try {
            Cipher cipher = Cipher.getInstance(format);
//            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes("utf-8"));
            cipher.init(Cipher.ENCRYPT_MODE, keyspecAes);
            byte[] encrypted = cipher.doFinal(dataBytes);
            return encrypted;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 使用AES解密
     * @since 0.0.11
     */
    public String decrypt(String data){
        if(StringUtils.isEmpty(data)){
            return null;
        }
        try {
            byte[] decrypted = decrypt(Base64.decodeBase64(data));
            return new String(decrypted,"utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 使用AES解密
     * @since 0.0.11
     */
    public byte[] decrypt(byte[] encrypted){
        if(encrypted==null){
            return null;
        }
        try {
            Cipher cipher = Cipher.getInstance(format);
//            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

            cipher.init(Cipher.DECRYPT_MODE, keyspecAes);

            byte[] original = cipher.doFinal(encrypted);
            return original;
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
